package com.example.wacoffee_user.utils;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;


import java.util.Properties;

public class MailUtil {
    public static void sendEmailCode(String targetEmail,String authCode) {
        final String from = "1963244380@qq.com";
        final String password = "fydkkwyrnuodbeca";
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com"); // SMTP 主机
        props.put("mail.smtp.port", "465"); // SSL 端口
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.auth", "true");
        jakarta.mail.Session session = Session.getDefaultInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from, "无爱咖啡"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(targetEmail));
            message.setSubject("注册验证码");
            message.setText("您的验证码为：" + authCode + "（有效期3分钟）");

            Transport.send(message);
            System.out.println("验证码邮件发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("邮件发送失败: " + e.getMessage());
        }
    }
}
